package com.atguigu.controller;

import com.atguigu.common.config.exception.MyException;
import com.atguigu.model.system.SysUser;
import com.atguigu.result.Result;
import com.atguigu.service.SysUserService;
import com.atguigu.utils.JwtHelper;
import com.atguigu.utils.MD5;
import com.atguigu.vo.system.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=null;
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);
        if (sysUser==null){
            throw new MyException(201,"用户不存在");
        }
//        lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(SysUser::getUsername,username);
//        lambdaQueryWrapper.eq(SysUser::getPassword,password);
//        SysUser sysUser1 = sysUserService.getOne(lambdaQueryWrapper);
        password = MD5.encrypt(password);
        if (!password.equals(sysUser.getPassword())){
            throw new MyException(201,"密码不正确");
        }
        if (sysUser.getStatus()!=1){
            throw new MyException(201,"用户被禁止");
        }
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        Map<String,Object> map=new HashMap();
        map.put("token",token);
        return Result.ok(map);
    }
    @GetMapping("info")
    public Result info(HttpServletRequest request){
//        map.put("roles","[admin]");
//        map.put("name","admin");
//        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        String token = request.getHeader("token");
        Long userId = JwtHelper.getUserId(token);
        Map<String, Object> map=sysUserService.getInfo(userId);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }
}
